<template>
  <div class="activities-page">
    <div class="header">
      <h2>签到活动管理</h2>
      <div class="actions">
        <el-button type="primary" @click="showCreateNormalDialog">创建普通签到</el-button>
        <el-button type="warning" @click="showCreateCodeDialog">创建签到码签到</el-button>
        <el-button type="success" @click="showCreateQRCodeDialog">创建二维码签到</el-button>
        <el-button type="info" @click="showCreateGestureDialog">创建九宫格签到</el-button>
        <el-button type="danger" @click="showCreateLocationDialog">创建位置签到</el-button>
        <el-button type="default" @click="refreshActivities">刷新</el-button>
      </div>
    </div>

    <el-table :data="activities" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column label="签到类型" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTag(scope.row.type)">{{ getActivityType(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" min-width="200">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" min-width="200">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="380">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="showEditDialog(scope.row)"
            :disabled="scope.row.type !== 'normal' && scope.row.type !== 'location'"
          >
            修改
          </el-button>
          <el-button 
            v-if="scope.row.type === 'code'"
            type="warning" 
            size="small"
          >
            密码: {{ scope.row.secret }}
          </el-button>
          <el-button 
            v-if="scope.row.type === 'qr'"
            type="success" 
            size="small" 
            @click="showQRCode(scope.row.id)"
          >
            查看二维码
          </el-button>
          <el-button 
            v-if="scope.row.type === 'gesture'"
            type="info" 
            size="small"
          >
            手势: {{ scope.row.gesturePoint }}
          </el-button>
          <el-button 
            v-if="scope.row.type === 'location'"
            type="info" 
            size="small"
          >
            位置签到
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建普通签到对话框 -->
    <el-dialog v-model="normalDialogVisible" title="创建普通签到" width="500px">
      <el-form :model="normalForm" label-width="120px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="normalForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="normalForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="normalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createNormalActivity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 创建签到码签到对话框 -->
    <el-dialog v-model="codeDialogVisible" title="创建签到码签到" width="500px">
      <el-form :model="codeForm" label-width="120px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="codeForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="codeForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="签到码">
          <el-input v-model="codeForm.signCode" placeholder="请输入签到码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="codeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createCodeActivity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 创建二维码签到对话框 -->
    <el-dialog v-model="qrDialogVisible" title="创建二维码签到" width="500px">
      <el-form :model="qrForm" label-width="120px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="qrForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="qrForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="qrDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createQRCodeActivity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 创建九宫格签到对话框 -->
    <el-dialog v-model="gestureDialogVisible" title="创建九宫格签到" width="500px">
      <el-form :model="gestureForm" label-width="120px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="gestureForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="gestureForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="手势坐标点">
          <div class="gestures-grid">
            <div
              v-for="(point, index) in nineGrid"
              :key="index"
              class="grid-item"
              @click="toggleGesturePoint(index + 1)"
              :class="{ active: gestureForm.gesturePoint.includes((index + 1).toString()) }"
            >
              {{ index + 1 }}
            </div>
          </div>
          <el-input
            v-model="gestureForm.gesturePoint"
            placeholder="请选择手势坐标点（例如：1,2,3,4）"
            readonly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetGestureForm">重置</el-button>
        <el-button @click="gestureDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createGestureActivity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 创建位置签到对话框 -->
    <el-dialog v-model="locationDialogVisible" title="创建位置签到" width="800px">
      <div class="location-dialog-content">
        <div class="map-container" style="flex: 1; height: 100%;">
          <amap :center="[locationForm.longitude, locationForm.latitude]" :zoom="15" @init="handleMapInit">
            <amap-marker v-if="locationForm.longitude && locationForm.latitude" :position="[locationForm.longitude, locationForm.latitude]" />
            <amap-geolocation @complete="handleGeolocationComplete" />
          </amap>
        </div>
        <div class="location-form-container" style="width: 300px; padding: 20px;">
          <el-form :model="locationForm" label-width="120px">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="locationForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="locationForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="经度">
              <el-input-number v-model="locationForm.longitude" :precision="6" :step="0.000001" />
            </el-form-item>
            <el-form-item label="纬度">
              <el-input-number v-model="locationForm.latitude" :precision="6" :step="0.000001" />
            </el-form-item>
            <el-form-item label="允许误差范围（米）">
              <el-input-number v-model="locationForm.radius" :min="1" :max="1000" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="locationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createLocationActivity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 显示二维码对话框 -->
    <el-dialog v-model="qrCodeDisplayVisible" title="签到二维码" width="400px" center>
      <div class="qrcode-display">
        <img v-if="qrcodeData" :src="'data:image/png;base64,' + qrcodeData" alt="签到二维码" />
      </div>
    </el-dialog>

    <!-- 修改签到对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改签到活动" width="500px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="editForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { initAMapApiLoader } from '@vuemap/vue-amap'
import {
  getSignActivities,
  createNormalSignActivity,
  createCodeSignActivity,
  createQRCodeSignActivity,
  createGestureSignActivity,
  createLocationSignActivity,
  deleteSignActivity,
  getSignActivityQRCode,
  updateSignActivity
} from '@/api/teacher'
import { ElMessage, ElMessageBox } from 'element-plus'

// 初始化高德地图 API 加载器
initAMapApiLoader({
  key: '32c78303070a7b7d221b04d0927c5ff8', // 替换为你的高德地图API密钥
  plugin: ['AMap.Marker', 'AMap.Geolocation']
})

export default {
  name: 'TeacherActivities',
  setup() {
    const activities = ref([])
    const loading = ref(false)
    const normalDialogVisible = ref(false)
    const codeDialogVisible = ref(false)
    const qrDialogVisible = ref(false)
    const gestureDialogVisible = ref(false)
    const locationDialogVisible = ref(false)
    const qrCodeDisplayVisible = ref(false)
    const qrcodeData = ref('')

    const nineGrid = ref([1, 2, 3, 4, 5, 6, 7, 8, 9])

    const normalForm = ref({
      startTime: '',
      endTime: ''
    })

    const codeForm = ref({
      startTime: '',
      endTime: '',
      signCode: ''
    })

    const qrForm = ref({
      startTime: '',
      endTime: ''
    })

    const gestureForm = ref({
      startTime: '',
      endTime: '',
      gesturePoint: ''
    })

    const locationForm = ref({
      startTime: '',
      endTime: '',
      longitude: 0,
      latitude: 0,
      radius: 50
    })

    const editDialogVisible = ref(false)
    const editForm = ref({
      id: null,
      startTime: '',
      endTime: ''
    })

    const mapInstance = ref(null)

    const getActivityType = (type) => {
      const types = {
        normal: '普通签到',
        code: '签到码',
        qr: '二维码',
        gesture: '九宫格',
        location: '位置签到'
      }
      return types[type] || type
    }

    const getTypeTag = (type) => {
      const tags = {
        normal: '',
        code: 'warning',
        qr: 'success',
        gesture: 'info',
        location: 'danger'
      }
      return tags[type] || 'info'
    }

    const showCreateNormalDialog = () => {
      normalForm.value = { startTime: '', endTime: '' }
      normalDialogVisible.value = true
    }

    const showCreateCodeDialog = () => {
      codeForm.value = { startTime: '', endTime: '', signCode: '' }
      codeDialogVisible.value = true
    }

    const showCreateQRCodeDialog = () => {
      qrForm.value = { startTime: '', endTime: '' }
      qrDialogVisible.value = true
    }

    const showCreateGestureDialog = () => {
      gestureForm.value = { startTime: '', endTime: '', gesturePoint: '' }
      gestureDialogVisible.value = true
    }

    const showCreateLocationDialog = () => {
      locationForm.value = {
        startTime: '',
        endTime: '',
        longitude: 0,
        latitude: 0,
        radius: 50
      }
      locationDialogVisible.value = true
    }

    const createNormalActivity = async () => {
      try {
        const response = await createNormalSignActivity(normalForm.value)
        if (response.code === 200) {
          ElMessage.success(response.message || '普通签到创建成功')
          normalDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      }
    }

    const createCodeActivity = async () => {
      try {
        const response = await createCodeSignActivity(codeForm.value)
        if (response.code === 200) {
          ElMessage.success(response.message || '签到码签到创建成功')
          codeDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      }
    }

    const createQRCodeActivity = async () => {
      try {
        const response = await createQRCodeSignActivity(qrForm.value)
        if (response.code === 200) {
          ElMessage.success(response.message || '二维码签到创建成功')
          qrDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      }
    }

    const createGestureActivity = async () => {
      try {
        if (!gestureForm.value.gesturePoint) {
          ElMessage.error('请输入手势坐标点')
          return
        }

        const points = gestureForm.value.gesturePoint.split(',')
        if (points.length !== 4) {
          ElMessage.error('手势坐标点必须为4个')
          return
        }

        const response = await createGestureSignActivity(gestureForm.value)
        if (response.code === 200) {
          ElMessage.success(response.message || '九宫格签到创建成功')
          gestureDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      }
    }

    const createLocationActivity = async () => {
      try {
        if (!locationForm.value.longitude || !locationForm.value.latitude) {
          ElMessage.error('请设置有效的位置坐标')
          return
        } 

        const response = await createLocationSignActivity({
          startTime: locationForm.value.startTime,
          endTime: locationForm.value.endTime,
          longitude: locationForm.value.longitude,
          latitude: locationForm.value.latitude,
          radius: locationForm.value.radius
        })

        if (response.code === 200) {
          ElMessage.success(response.message || '位置签到创建成功')
          locationDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      }
    }

    const showQRCode = async (id) => {
      try {
        const response = await getSignActivityQRCode(id)
        if (response.code === 200) {
          qrcodeData.value = response.data
          qrCodeDisplayVisible.value = true
        }
      } catch (error) {
        ElMessage.error('获取二维码失败：' + error.message)
      }
    }

    const handleDelete = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个签到活动吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteSignActivity(id)
        if (response.code === 200) {
          ElMessage.success(response.message || '删除成功')
          fetchActivities()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    }

    const fetchActivities = async () => {
      loading.value = true
      try {
        const response = await getSignActivities()
        if (response.code === 200) {
          activities.value = response.data
        }
      } catch (error) {
        ElMessage.error('获取活动列表失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    const refreshActivities = () => {
      fetchActivities()
    }

    const showEditDialog = (row) => {
      editForm.value = {
        id: row.id,
        startTime: row.startTime,
        endTime: row.endTime
      }
      editDialogVisible.value = true
    }

    const handleEdit = async () => {
      try {
        const response = await updateSignActivity(editForm.value.id, {
          startTime: editForm.value.startTime,
          endTime: editForm.value.endTime
        })
        if (response.code === 200) {
          ElMessage.success(response.message || '修改成功')
          editDialogVisible.value = false
          fetchActivities()
        }
      } catch (error) {
        ElMessage.error('修改失败：' + error.message)
      }
    }

    const formatDateTime = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      const second = date.getSeconds().toString().padStart(2, '0')
      return `${year}年${month}月${day}日${hour}时${minute}分${second}秒`
    }

    // 九宫格手势选择
    const toggleGesturePoint = (point) => {
      if (gestureForm.value.gesturePoint.includes(point.toString())) {
        gestureForm.value.gesturePoint = gestureForm.value.gesturePoint
          .split(',')
          .filter(p => p !== point.toString())
          .join(',')
      } else {
        if (!gestureForm.value.gesturePoint) {
          gestureForm.value.gesturePoint = point.toString()
        } else {
          gestureForm.value.gesturePoint += `,${point}`
        }
      }
    }

    const resetGestureForm = () => {
      gestureForm.value.gesturePoint = ''
    }

    // 地图初始化
    const handleMapInit = (map) => {
      mapInstance.value = map
      map.on('click', (e) => {
        locationForm.value.longitude = e.lnglat.getLng()
        locationForm.value.latitude = e.lnglat.getLat()
        if (mapInstance.value) {
          // 清除之前的标记
          mapInstance.value.remove(mapInstance.value.getOverlays())
          // 添加新标记
          
        }
      })
    }

    // 地理定位完成
    const handleGeolocationComplete = (position) => {
      locationForm.value.longitude = position.lnglat.getLng()
      locationForm.value.latitude = position.lnglat.getLat()
    }

    onMounted(() => {
      fetchActivities()
    })

    return {
      activities,
      loading,
      normalDialogVisible,
      codeDialogVisible,
      qrDialogVisible,
      gestureDialogVisible,
      locationDialogVisible,
      qrCodeDisplayVisible,
      qrcodeData,
      nineGrid,
      normalForm,
      codeForm,
      qrForm,
      gestureForm,
      locationForm,
      editDialogVisible,
      editForm,
      getActivityType,
      getTypeTag,
      showCreateNormalDialog,
      showCreateCodeDialog,
      showCreateQRCodeDialog,
      showCreateGestureDialog,
      showCreateLocationDialog,
      createNormalActivity,
      createCodeActivity,
      createQRCodeActivity,
      createGestureActivity,
      createLocationActivity,
      showQRCode,
      handleDelete,
      refreshActivities,
      showEditDialog,
      handleEdit,
      formatDateTime,
      toggleGesturePoint,
      resetGestureForm,
      handleMapInit,
      handleGeolocationComplete
    }
  }
}
</script>

<style scoped>
.activities-page {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.qrcode-display {
  text-align: center;
}

.qrcode-display img {
  max-width: 300px;
  margin: 20px auto;
}

/* 九宫格样式 */
.gestures-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.grid-item {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
  user-select: none;
}

.grid-item.active {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

/* 位置签到对话框样式 */
.location-dialog-content {
  display: flex;
  height: 500px;
}

.map-container {
  flex: 1;
  height: 100%;
}

.location-form-container {
  width: 300px;
  padding: 20px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-dialog) {
  min-width: 500px;
}
</style>